<?php
use Swoole\Http\Server;

require("../util/DBUtil.php");
$patterns =[
	"POST"=>"/^\/user$/i",
	"GET"=>"/^\/user\/(\d+)$/i"
]; 
$functions = [
	"POST"=>function($matchs,$request){
			//post传来的信息
			$getPost = json_decode($request->rawContent(),1);
			$ret = (new DBUtil())->saveToDB($getPost,'user');
			if($ret){
				return ['status'=>'新增成功'];
			}
			return false;
	},
	"GET"=>function($matchs,$request){
		$userid=0;
		if($matchs){
			$userid=$matchs[1];
			return (new DBUtil())->getData(['userid'=>$userid],"user");
		}
		return false;
	}
];
$http = new Server("0.0.0.0", 9503);
$http->on('request', function ($request, $response) use($patterns,$functions) {
	$response->header('Content-Type', "application/json");
	$requestPath = $request->server['request_uri'];//请求路径
	$requestMethod = $request->server['request_method'];//请求方式

	if(isset($patterns[$requestMethod]) && preg_match($patterns[$requestMethod], $requestPath,$matchs)){
		$func = $functions[$requestMethod];
		$result = $func($matchs,$request);
	}
	if($result){
		  $response->end(json_encode($result));
	}else{
 		  $response->end('nothing to do');
	}
  
});
$http->start();